<template>
    <view class="group-container">
        <!-- 自定义导航栏 -->
        <u-navbar 
            title="我的群聊" 
            autoBack
            rightText="创建"
            @rightClick="createGroup"
            :customStyle="{ backgroundColor: '#fff' }"
        >
            <!-- 中间搜索框 -->
            <view slot="center" class="nav-center">
                <u-search 
                    placeholder="搜索群聊" 
                    @click="handleSearch" 
                    :showAction="false"
                    :customStyle="{
                        backgroundColor: '#f5f5f5',
                        height: '60rpx',
                        borderRadius: '30rpx'
                    }"
                ></u-search>
            </view>
        </u-navbar>

        <!-- 列表内容 -->
        <scroll-view class="group-list-container" scroll-y @scrolltolower="reachBottom">
			<block v-if="pendingList.length > 0">
			    <view class="pending-section">
			        <view class="section-title">群聊邀请</view>
			        <view class="pending-item" v-for="(item, index) in pendingList" :key="index">
			            <view class="top-row">
			                <u-image :src="item.avatarUrl" width="80rpx" height="80rpx" border-radius="16"></u-image>
			                <view class="invite-info">
			                    {{ item.name }} · 邀请您加入群聊
			                </view>
			        
			                <!-- 按钮移动到这里 -->
			                <view class="action-buttons">
			                    <u-button 
			                        size="mini"
			                        shape="circle" 
			                        icon="checkmark" 
			                        iconSize="14"
			                        type="success"
			                        @click="agreeRequest(item)"
			                    ></u-button>
			                    <u-button 
			                        size="mini"
			                        shape="circle" 
			                        icon="close" 
			                        iconSize="14"
			                        type="error"
			                        @click="refuseRequest(item)"
			                    ></u-button>
			                </view>
			            </view>
			        </view>
			    </view>
			</block>
			
            <block v-if="groupList.length > 0">
                <group-list 
                    v-for="(item, index) in groupList" 
                    :key="index" 
                    :item="item"
                />
                <u-loadmore :status="loadStatus" />
            </block>
            <block v-else>
                <u-empty mode="list" text="暂无群聊"></u-empty>
            </block>
        </scroll-view>

        <!-- 浮动按钮 - 创建群聊 -->
        <u-button 
            class="floating-btn" 
            shape="circle" 
            size="medium"
            @click="createGroup"
        >+</u-button>
    </view>
</template>

<script>
import GroupList from '@/pages/groups/cpns/group_list.vue';
import { groupList } from '@/utils/data/data.js';
import { GroupApi,GroupMembersApi } from '@/api/index.js';
import { loadAllParams } from '@/api/page';
import websocketMixin from '@/utils/mixins/websocketMixin'


export default {
	mixins: [websocketMixin],
    components: {
        GroupList
    },
    data() {
        return {
            loadStatus: 'loadmore',
            groupList: [],
			pendingList: []
        };
    },
    onShow() {
        this.initData();
        uni.$on('groupCreated', this.handleGroupCreated);
    },
    onUnload() {
        uni.$off('groupCreated', this.handleGroupCreated);
    },
    methods: {
	onInviteMessage(data){
		this.initData();
	},
    async initData() {
        this.loadStatus = 'loading';
		console.log(getApp().globalData);
            try {
				// 获取待处理的入群申请
				const pendingRes = await GroupApi.listByInvite();
				this.pendingList = pendingRes.data || [];
				
				// 获取群组列表
                const res = await GroupApi.listByLocal(loadAllParams);
                if (res && res.code === 200 && res.data && Array.isArray(res.data.list)) {
                    this.groupList = res.data.list;
                    //uni.showToast({ title: `共加载 ${this.groupList.length} 个群组` });
                } else {
                    uni.showToast({ title: '数据格式异常', icon: 'none' });
                    this.groupList = [];
                }
        
                this.loadStatus = 'loadmore';
        
            } catch (e) {
            console.error("读取群聊数据失败", e);
        }
    },
        handleGroupCreated(newGroup) {
            this.groupList.unshift(newGroup);
        },
        createGroup() {
            uni.navigateTo({ url: '/pages/groups/create_group' });
        },
        handleSearch() {
            uni.navigateTo({ url: '/pages/search/search?type=group' });
        },
        reachBottom() {
            if (this.loadStatus !== 'loadmore') return;
            this.loadStatus = 'loading';
            setTimeout(() => {
                this.groupList.push(...this.groupList.slice(0, 5)); // 模拟加载更多
                this.loadStatus = 'nomore';
            }, 1000);
        },
		// 同意入群请求
		async agreeRequest(request) {
		    try {
		        await GroupMembersApi.agreeGroup(request.id);
		        uni.showToast({ title: '已同意', icon: 'success' });
		        this.pendingList = this.pendingList.filter(i => i.groupId !== request.groupId);
				this.initData();
		    } catch (err) {
		        uni.showToast({ title: '操作失败', icon: 'none' });
		    }
		},
		// 拒绝入群请求
		async refuseRequest(request) {
		    try {
		        await GroupMembersApi.refuseGroup(request.id);
		        uni.showToast({ title: '已拒绝', icon: 'none' });
		        this.pendingList = this.pendingList.filter(i => i.groupId !== request.groupId);
		    } catch (err) {
		        uni.showToast({ title: '操作失败', icon: 'none' });
		    }
		}
    }
};
</script>

<style lang="scss" scoped>
.group-container {
	padding-bottom: 120rpx;
}

/* 导航栏 */
.nav-center {
	width: 100%;
	margin-left: 70rpx;
}

/* 标签页 */
.nav-tabs {
	display: flex;
	justify-content: space-around;
	align-items: center;
	height: 80rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #eee;
}

.tab-item {
	flex: 1;
	text-align: center;
	font-size: 30rpx;
	color: #666;
	position: relative;

	&.active .tab-title {
		color: $uni-color-green;
		font-weight: bold;
	}
}

.tab-title {
	line-height: 80rpx;
}

.ml-10 {
	margin-left: 10rpx;
	color: $uni-color-green;
}

/* 轮播区域 */
.group-swiper {
	height: calc(100vh - 180rpx);
}

.group-scroll {
	padding: 20rpx;
}

/* 浮动按钮 */
.floating-btn {
	position: fixed;
	right: 40rpx;
	bottom: 100rpx;
	width: 90rpx;
	height: 90rpx;
	font-size: 48rpx;
	background-color: #07C160;
	color: #fff;
	z-index: 999;
}

.pending-section {
	padding: 30rpx;
	background-color: #fff;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 28rpx;
	color: #999;
	text-align: center;
	margin-bottom: 30rpx;
}

.divider {
	height: 1rpx;
	background-color: #eee;
	margin-top: 20rpx;
}
.pending-item {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    margin-bottom: 30rpx;
}

.top-row {
    display: flex;
    align-items: center;
    gap: 20rpx;

    // 如果你希望按钮始终靠右对齐，并且不被压缩
    > .invite-info {
        flex: 1; /* 占据中间空间 */
    }

    > .action-buttons {
        display: flex;
        gap: 10rpx;
    }
}
</style>
